﻿using System;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.Sugar;
using Roles = Medianamik.Core.Security.Roles;
using Medianamik.Core.Security;
using System.Globalization;

namespace Medianamik.UI.Web.ModalWindows
{
    public partial class DeleteNodeWindow : BasePage
    {
        const string _deleteInstanceOption = "1";
        const string _deleteAllInstancesOption = "2";
        const string _deleteBranchOption = "3";

        protected void Page_Load(object sender, EventArgs e)
        {
            //Ne pas prendre cette culture mais bien celle passée en param
            //_cultureName = MedianamikContext.Current.EditionCulture.Name;
            if (!Page.IsPostBack)
            {
                if (!ValidateParameters())
                {
                    return;
                }

                if (CultureName.Length == 0 || !Node.Instances.Exists(CultureName))
                {
                    if (Node.HasChildren)
                    {
                        textLabel.Text =
                            (string)GetGlobalResourceObject("Medianamik_ContentManagement", "ConfirmDeleteBranchText");
                    }
                    else
                    {
                        textLabel.Text =
                            (string)GetGlobalResourceObject("Medianamik_ContentManagement", "ConfirmDeleteNodeText");
                    }
                }
                else
                {
                    var instancesCount = Node.Instances.Count;
                    if (instancesCount > 1)
                    {
                        if (Node.HasChildren)
                        {
                            if (MedianamikContext.Current.MedianamikUser.CanDeleteNodeBranch)
                            {
                                deleteOptions.Items.Add(GetListItem(_deleteInstanceOption));
                                deleteOptions.Items.Add(GetListItem(_deleteBranchOption));
                            }
                            else
                            {
                                textLabel.Text =
                                    (string)
                                    GetGlobalResourceObject("Medianamik_ContentManagement", "ConfirmDeleteInstanceText");
                            }
                        }
                        else
                        {
                            if (Neutral)
                            {
                                textLabel.Text =
                                    (string)
                                    GetGlobalResourceObject("Medianamik_ContentManagement", "ConfirmDeleteNodeText");
                            }
                            else
                            {
                                if (MedianamikContext.Current.MedianamikUser.CanDeleteAllInstancesOfANode)
                                {
                                    deleteOptions.Items.Add(GetListItem(_deleteInstanceOption));
                                    deleteOptions.Items.Add(GetListItem(_deleteAllInstancesOption));
                                }
                                else
                                {
                                    textLabel.Text = (string)GetGlobalResourceObject("Medianamik_ContentManagement",
                                                                "ConfirmDeleteInstanceText");
                                }
                            }
                        }
                    }
                    else
                    {
                        if (Node.HasChildren)
                        {
                            textLabel.Text = (string)GetGlobalResourceObject("Medianamik_ContentManagement", "ConfirmDeleteBranchText");
                        }
                        else
                        {
                            textLabel.Text = (string)GetGlobalResourceObject("Medianamik_ContentManagement", "ConfirmDeleteNodeText");
                        }
                    }
                }

                if (deleteOptions.Items.Count > 1)
                {
                    textLabel.Text = (string)GetGlobalResourceObject("Medianamik_Global", "WhatWouldYouLikeToDelete");
                    deleteOptions.Visible = true;
                }

            }
        }

        protected virtual bool Destroy
        {
            get
            {
                if (ViewState["Destroy"] == null)
                {
                    if (!String.IsNullOrEmpty(Request.QueryString["destroy"])
                        && Request.QueryString["destroy"].Equals("true", StringComparison.OrdinalIgnoreCase))
                    {
                        ViewState["Destroy"] = true;
                    }
                    else
                    {
                        ViewState["Destroy"] = false;
                    }
                }
                return (bool)ViewState["Destroy"];
            }
        }

        private bool Neutral
        {
            get
            {
                if (ViewState["Neutral"] == null)
                {
                    if (!String.IsNullOrEmpty(Request.QueryString["neutral"])
                         && Request.QueryString["neutral"].Equals("true", StringComparison.OrdinalIgnoreCase))
                    {
                        ViewState["Neutral"] = true;
                    }
                    else
                    {
                        ViewState["Neutral"] = false;
                    }
                }
                return (bool)ViewState["Neutral"];
            }
        }

        protected virtual Guid? NodeId
        {
            get
            {
                if (ViewState["NodeId"] == null)
                {
                    Guid nodeId;
                    if (StringHelper.IsGuid(NodeIdParamValue, out nodeId))
                    {

                        ViewState["NodeId"] = nodeId;
                    }
                }
                return ViewState["NodeId"] as Guid?;
            }
        }

        private string NodeIdParamValue
        {
            get
            {
                if (ViewState["NodeIdParamValue"] == null)
                {
                    ViewState["NodeIdParamValue"] = Request.QueryString[DefaultParamNames.NodeID] ?? string.Empty;
                }
                return (string)ViewState["NodeIdParamValue"];
            }
        }

        private Node _node;
        protected virtual Node Node
        {
            get
            {
                if (_node == null)
                {
                    if (NodeId.HasValue)
                    {
                        _node = NodeManager.GetNode(NodeId.Value);
                    }
                }
                return _node;
            }
        }

        private bool CultureNameParamExists
        {
            get
            {
                return Request.QueryString.AllKeys.Any(k => k.Equals("culturename", StringComparison.OrdinalIgnoreCase));
            }
        }

        protected virtual string CultureName
        {
            get
            {
                if (ViewState["CultureName"] == null)
                {
                    ViewState["CultureName"] = CultureNameParamExists
                                                   ? Request.QueryString["culturename"]
                                                   : string.Empty;
                }
                return (string)ViewState["CultureName"];
            }

        }

        void UltimatumReached(object sender, EventArgs e)
        {
            DisplayDenyMessage((string)GetGlobalResourceObject("Medianamik_LockManagement", 
                "UltimatumReached"));
        }

        public bool ValidateParameters()
        {
            if (String.IsNullOrEmpty(NodeIdParamValue))
            {
                DisplayDenyMessage(String.Concat(
                    (string)GetGlobalResourceObject("Medianamik_Global", "ArgumentNullException"), " ",
                    "NodeID"));
                return false;
            }

            if (!CultureNameParamExists)
            {
                DisplayDenyMessage(String.Concat(
                    (string)GetGlobalResourceObject("Medianamik_Global", "ArgumentNullException"), " ",
                    "CultureName"));
                return false;
            }

            Guid dummy;
            if (!StringHelper.IsGuid(NodeIdParamValue, out dummy))
            {
                DisplayDenyMessage(String.Concat(
                (string)GetGlobalResourceObject("Medianamik_Global", "ArgumentException"), " ",
                "NodeID"));
                return false;
            }
            if (Node == null)
            {
                DisplayDenyMessage(String.Concat(
                (string)GetGlobalResourceObject("Medianamik_Global", "NodeNotFound"), " ",
                NodeIdParamValue));
                return false;
            }

            if (!Roles.UserHasRight(Node, SecurityLevels.Delete))
            {
                DisplayDenyMessage(String.Concat(
                (string)GetGlobalResourceObject("Medianamik_SecurityManagement", "DenyDeleteNode"), " ",
                NodeIdParamValue));
                return false;
            }

            if (CultureName.Length == 0 || !Node.Instances.Exists(CultureName))
            {
                if (Node.HasChildren)
                {
                    if (!MedianamikContext.Current.MedianamikUser.CanDeleteNodeBranch)
                    {
                        DisplayDenyMessage((string)GetGlobalResourceObject("Medianamik_Global", "DenyDeleteBranch"));
                        return false;
                    }
                }
                else
                {
                    if (!Neutral && !MedianamikContext.Current.MedianamikUser.CanDeleteAllInstancesOfANode)
                    {
                        DisplayDenyMessage((string)GetGlobalResourceObject("Medianamik_Global", "DenyDeleteAllInstances"));
                        return false;
                    }
                }
            }

            int instancesCount = Node.Instances.Count;
            if (instancesCount == 1 && Node.HasChildren && !MedianamikContext.Current.MedianamikUser.CanDeleteNodeBranch)
            {
                DisplayDenyMessage((string)GetGlobalResourceObject("Medianamik_SecurityManagement", "DenyDeleteBranch"));
                return false;
            }

            return true;
        }

        private ListItem GetListItem(string pDeleteOption)
        {
            switch (pDeleteOption)
            {
                case _deleteInstanceOption:
                    return new ListItem((string)GetGlobalResourceObject("Medianamik_SecurityManagement", "DeleteInstance") + " "
                                + new CultureInfo(CultureName).DisplayName
                                , _deleteInstanceOption);
                case _deleteAllInstancesOption:
                    return new ListItem((string)GetGlobalResourceObject("Medianamik_SecurityManagement", "DeleteAllInstances"),
                                     _deleteAllInstancesOption);
                case _deleteBranchOption:
                    return new ListItem((string)GetGlobalResourceObject("Medianamik_SecurityManagement", "DeleteBranch"),
                                     _deleteBranchOption);
                default:
                    throw new ArgumentException(pDeleteOption);
            }
        }

        protected virtual DropDownList deleteOptionsAccessor
        {
            get
            { return deleteOptions; }
            set
            { deleteOptions = value; }
        }

        protected internal void DeleteNode(object sender, EventArgs e)
        {
            if (deleteOptionsAccessor.Visible)
            {
                switch (deleteOptionsAccessor.SelectedValue)
                {
                    case _deleteInstanceOption:
                        Node.RemoveNodeInstance(CultureName);
                        NodeManager.SaveNode(Node);
                        break;
                    case _deleteAllInstancesOption:
                        if (Destroy)
                            NodeManager.DestroyNode(Node);
                        else
                            NodeManager.DeleteNode(Node);
                        break;
                    case _deleteBranchOption:
                        NodeManager.DeleteBranch(Node.ID, Destroy);
                        break;
                }
            }
            else
            {
                if (Node.HasChildren)
                {
                    NodeManager.DeleteBranch(NodeId.Value, Destroy);
                }
                else
                {
                    if (Destroy)
                        NodeManager.DestroyNode(Node);
                    else
                        NodeManager.DeleteNode(Node);
                }

            }

            DisplayMessage(GetMessageToDisplayWhenDeleteAccomplished());
            ScriptManager.RegisterStartupScript(this, typeof(DeleteNodeWindow),
                "CloseWindow", "Sys.Application.add_load(function() { closeWindow(true); });", true);
        }

        protected virtual string GetMessageToDisplayWhenDeleteAccomplished()
        {
            return (string)GetGlobalResourceObject("Medianamik_ContentManagement", "DeletingNodeInstanceText");
        }

        private void DisplayDenyMessage(string message)
        {
            scriptBlock.Visible = false;
            mainPlaceHolder.Visible = false;
            denyPlaceHolder.Visible = true;
            denyMessage.Text = message;
        }

        protected virtual void DisplayMessage(string message)
        {
            mainPlaceHolder.Visible = false;
            denyPlaceHolder.Visible = true;
            denyMessage.Text = message;
        }
    }
}